<template>
    <div class="page-body-div">
      <el-tabs v-model="activeName" @tab-click="handleClick" type="border-card">
        <el-tab-pane label="Begin" name="tabOne" disabled/>
        <el-tab-pane label="发送账号" name="first">
          <div class="menu-tab-div">
            <sender-account :addresser.sync="form.Addresser" :addresserLabel.sync="form.AddresserLabel" />
          </div>
        </el-tab-pane>
        <el-tab-pane label=">>>" name="tabTwo" disabled/>
        <el-tab-pane label="收件列表" name="second">
          <div class="menu-tab-div">
            <receiver-list :addressee.sync="form.Addressee" :emails-temp="emailsTemp" />
          </div>
        </el-tab-pane>
        <el-tab-pane label=">>>" name="tabThree" disabled/>
        <el-tab-pane label="编辑邮件" name="third">
          <div class="menu-tab-div">
            <div class="menu-tab-div-body">
              <el-divider></el-divider>
              <div>
                <el-form ref="form"
                  :model="form"
                  label-width="80px">
                  <el-form-item label="邮件主题:">
                    <el-input v-model="form.EmailSubject" show-word-limit></el-input>
                  </el-form-item>
                  <el-form-item label="正文:">
                    <el-row style="float:left;">
                      <el-button type="success" size="mini" plain @click="handleSelectTemplate">选择模板</el-button>
                    </el-row>
                    <div style="clear:both;"></div>
                    <tinymce-page value=" " v-model="form.EmailContent" :height="500" ></tinymce-page>
                  </el-form-item>
                </el-form>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label=">>>" name="tabFour" disabled/>
        <el-tab-pane label="发送参数" name="fourth">
          <div class="menu-tab-div">
            <div class="menu-tab-div-body">
              <el-divider></el-divider>
              <div style="height:40%;margin:20px 50px;">
                <el-row :gutter="20">
                  <!-- <el-col :span="18" :offset="6"> -->
                    <!-- <p style="font-weight:400;color:#1f2f3d;font-size:20px;float:left;display:block;margin-left: 9px;">新增邮箱授权</p> -->
                  <!-- </el-col> -->
                  <el-col :span="18" :offset="6">
                    <el-form ref="form" :model="form" :rules="form" label-width="80px" style="width:650px;text-align:center;border:1px solid grey;border-radius:10px;padding:30px;margin:10px;">
                      <el-form-item label="任务名称:" prop="Title">
                        <el-input v-model="form.Title" :minlength="1" show-word-limit :maxlength="50" clearable></el-input>
                      </el-form-item>
                      <el-form-item label="回件地址:" prop="ReplyEmail">
                        <el-input v-model="form.ReplyEmail"></el-input>
                      </el-form-item>
                      <div>
                        <p sytle="color:red;">更多配置,敬请期待...</p>
                      </div>
                    </el-form>
                  </el-col>
                </el-row>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label=">>>" name="tabFive" disabled/>
        <el-tab-pane label="开始发送" name="fifth">
          <div class="menu-tab-div">
            <div class="menu-tab-div-body">
              <el-divider></el-divider>
              <div style="margin:0px 0px 20px 10px;">
                <span style="padding-right:100px;">
                  <el-button  v-waves class="filter-item" type="primary" icon="el-icon-caret-right" size="mini" @click="submitFreeSend"  style="width:150px;margin-right:100px;">开始</el-button>
                  <el-button  v-waves class="filter-item" type="danger" icon="el-icon-switch-button" size="mini" @click="" style="width:150px;" disabled>停止</el-button>
                </span>
              </div>
              <el-divider></el-divider>
              <div>
                <el-form ref="form" :model="form" label-width="380px">
                  <el-form-item label="完成进度:">
                    <el-progress style="width:800px;line-height: 32px;" :text-inside="true" :stroke-width="24" :percentage="sendPercent" status="success" disabled></el-progress>
                  </el-form-item>
                  <el-form-item label="发送方式:">
                    <el-radio-group v-model="radio" style="float:left;width:300px;">
                      <el-radio :label="3" border>随机发送</el-radio>
                      <el-radio :label="6" border>顺序发送</el-radio>
                    </el-radio-group>
                    <span style="float:left;margin-left:50px;">总发送 {{ form.Addressee.length }} 条, 已发送 {{ sendCount }} 条， 失败 {{ failedCount }} 条</span>
                  </el-form-item>
                </el-form>
              </div>
              <el-divider></el-divider>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="End" name="tabSix" disabled/>
      </el-tabs>
      <select-template :show.sync="showSelectTemplateVisible" @updateTemplate="handleTemplateChange" />

    </div>
</template>
<script>
import TinymcePage from '../Tinymce/index.vue'
import SelectTemplate from '../emailTemplate/selectTemplate.vue'

import { getAction, postAction } from '@/api/common'
import * as echarts from 'echarts'
import { SendMode } from '@/utils/client/formProcessProxy'
import { validateEmail } from '@/utils/validate'
import ReceiverList from './addStep/receiverList'
import SenderAccount from '@/views/email/emailSendFree/addStep/senderAccount'
export default {

  name: 'baseform',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '600px'
    },
    height: {
      type: String,
      default: '500px'
    },
    emailsTemp: ''

  },
  components: {
    SenderAccount,
    ReceiverList,
    TinymcePage,
    SelectTemplate

  },
  data: function() {
    return {
      radio: 3,
      /// //////////////////////////Public//////////////////////////////////
      activeName: 'first',
      form: {
        Title: '营销任务_' + this.getCurrentDate(2),
        Addresser: [],
        ShowAsEmail: false,
        ReplyEmail: '',
        Addressee: [],
        AddresserLabel: [],
        EmailSubject: '',
        EmailContent: '',
        TimingTransmission: null,
        TypeOfRequest: 'free',
        State: 1
      },

      searchAddresser: '',

      /// //////////////////////////编辑邮件//////////////////////////////////
      showSelectTemplateVisible: false,
      /// //////////////////////////验证规则//////////////////////////////////
      sendCount: 0,
      failedCount: 0
    }
  },
  computed: {
    sendPercent() {
      if (this.form.Addressee.length === 0) return 0
      return parseInt(this.sendCount / this.form.Addressee.length * 100)
    }
  },
  watch: {
    // show(val) {
    //   this.$emit('update:show', val)
    // }
  },
  created() {
    this.sendCount = 0
    this.failedCount = 0
    this.getInit()

    VUE.$on('Test', (res) => {
      console.log(res)
      const action = res.Complete ? 'Complete' : (res.First ? 'first' : "")
      const result = {
        Name: '暂无',
        ReceiverEmail: res.ReceiverEmail,
        SendingType: 1,
        SenderEmail: res.SenderEmail,
        State: res.State,
        Source: res.Source,
        MarketingTaskName: res.marketingTaskName,
        action,
      }
      postAction(result, 'EmailSendHistory/SendingFreeCreate')
        .then((resu) => {
          console.log('成功返回')
        })

      this.sendCount++
      if (res.State !== 1) this.failedCount++
    })
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.initChart()
    // })
  },
  beforeDestroy() {
    VUE.$off('Test')
  },

  methods: {
    // 编辑和弹出的初始化页面
    getInit() {

      // this.form.id = id || ''
      // // 显示弹出层
      // // 编辑的时候回显
      // this.$nextTick(() => {

      // })
    },
    handleClick(tab, event) {
    },

    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      const xAxisData = []
      const data = []
      const data2 = []
      for (let i = 0; i < 50; i++) {
        xAxisData.push(i.toString())
        data.push((Math.sin(i / 5) * (i / 5 - 10) + i / 6) * 5)
        data2.push((Math.sin(i / 5) * (i / 5 + 10) + i / 6) * 3)
      }
      const option = {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: [120, 200, 150, 80, 70, 110, 130],
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }]
      }
      this.chart.setOption(option)
    },
    querySearch(queryString, cb) {
      const restaurants = this.sendAccountOptions
      const results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },

    /// //////////////////////////Public////////////////////////////////////
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    /// //////////////////////////编辑邮件//////////////////////////////////
    handleSelectTemplate() {
      this.showSelectTemplateVisible = true
    },

    /// ///////////////////////////发送参数/////////////////////////////////

    /// ///////////////////////////开始发送/////////////////////////////////
    submitFreeSend() {
      // 检测每一个步骤的值是否缺省
      // 检测发送账号
      // this.refs.form.validateField('Addresser');
      // this.form.Addressee = this.form.AddresseeLabel
      if (this.form.Addresser.length === 0) {
        this.$message({
          message: '请检查【发送账号】',
          type: 'warning'
        })
        return false
      }
      // 检测收件列表
      if (this.form.Addressee.length === 0) {
        this.$message({
          message: '请检查【收件列表】',
          type: 'warning'
        })
        return false
      }
      // 检测编辑邮件
      if (this.form.EmailContent.length === 0 || this.form.EmailSubject.length === 0) {
        this.$message({
          message: '请检查【编辑邮件】',
          type: 'warning'
        })
        return false
      }
      // 检测开始发送的参数
      postAction(this.form, 'EmailMarketing/Create')
        .then((res) => {
          console.log(res)
          if (res.code === 20000) {
            this.$message({ message: '创建营销任务成功!开始发送...', type: 'success' })
            const model = res.data.model
            const readUrls = res.data.readUrls
            this.$common.ExeInvoke(formProcess => {
              const beforeSender = JSON.parse(model.addresser)
              const sender = beforeSender.map(m => ({ Account: m.EmailAddress, Password: m.Secret, MailType: { Name: m.Host?.substr(5), Smtp: m.Host, SSL: true, Port: m.Port } }))
              const beforeReceiver = JSON.parse(model.addressee)
              const receiver = beforeReceiver.map(m => ({ Name: m.Name, MailNick: m.Name, Mail: m.Addressee }))
              const content = readUrls.map(m => ({
                Title: model.emailSubject,
                Content: model.emailContent + `<img src="${m}">`
              }))
              this.sendCount = 0
              this.failedCount = 0
              let num = 0
              const timer = setInterval(() => {
                if (num >= receiver.length) {
                  clearInterval(timer)
                  return
                }
                formProcess.SendEmail(
                  JSON.stringify(sender), // 发件人Json数据
                  JSON.stringify([receiver[num]]), // 收件人Json数据
                  JSON.stringify([content[num]]), // 发件内容Json数据
                  1, // 最小间隔时间
                  50, // 最大间隔时间
                  '', // 昵称
                  SendMode.SMTP, // 发送模式：HTTP=0, SMTP=1, MOBILE=2
                  5, // 单个发件箱最大发送数量限制
                  100, // 单个发件箱总发送数量限制
                  false, // 是否设置单次邮件发送数量限制
                  999, // 单次邮件发送数量限制
                  '', // ReplyTo 回件地址
                  false, // 是否设置全局ADSL拨号设置
                  0, // ADSL连续发送数量限制
                  '', // 宽带名称
                  '', // 用户名
                  '', // 密码
                  false, // 是否启用全局设备换IP,
                  model.id,
                  model.marketingTaskName
                )

                num++
              }, 1000)
            })

            console.log('对接客户端')
            // return false
          } else {
            this.$message({
              message: '创建营销任务失败！发送失败！',
              type: 'warning'
            })
          }
          // this.resetForm("emailForm")
        })
      // this.$message({message: '发送成功',type: 'success'})
    },
    handleTemplateChange(val) {
      this.form.EmailContent = val
    },
    /**
      * 获取当前时间
      * format=1精确到天
      * format=2精确到分
    ***/
    getCurrentDate(format) {
      const now = new Date()
      const year = now.getFullYear() // 得到年份
      let month = now.getMonth()// 得到月份
      let date = now.getDate()// 得到日期
      const day = now.getDay()// 得到周几
      let hour = now.getHours()// 得到小时
      let minu = now.getMinutes()// 得到分钟
      let sec = now.getSeconds()// 得到秒
      month = month + 1
      if (month < 10) month = '0' + month
      if (date < 10) date = '0' + date
      if (hour < 10) hour = '0' + hour
      if (minu < 10) minu = '0' + minu
      if (sec < 10) sec = '0' + sec
      let time = ''
      // 精确到天
      if (format === 1) {
        time = year + '-' + month + '-' + date
      } else if (format === 2) { // 精确到分
        time = year + month + date + hour + minu + sec
      }
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
  /////////////////////////////Public//////////////////////////////////
  .page-body-div
  {
    padding:5px 5px 0px;
    background-color:white;
  }
  .menu-tab-div
  {
    padding:20px 0px 0px 20px;
    width:100%;
    height:830px;
  }
  .menu-tab-div-body
  {
    margin:10px;text-align:center;height:100%;
  }

  /////////////////////////////编辑邮件//////////////////////////////////
</style>
